package com.epro.dx.util;

import android.content.Context;
import android.os.AsyncTask;

import com.epro.dx.listenner.OnLoginSuccessedListenner;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.UserModel;
import com.weipu.common.util.StringUtil;

public class LoginUtilTask extends AsyncTask<Void, Void, String> {
	private OnLoginSuccessedListenner loginListenner;
	private Context context;
	private boolean isJumpLogin;
	private UserModel userModel;
	public LoginUtilTask(OnLoginSuccessedListenner listenner,Context context,boolean isJumpLogin) {
		this.loginListenner=listenner;
		this.context=context;
		this.isJumpLogin=isJumpLogin;
	}
	@Override
	protected String doInBackground(Void... arg0) {
		if(ActivityUtil.isLogin(context)){
			String account= StringUtil.getConfig(context,
					ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
			String password=StringUtil.getConfig(context,
					ServerConstant.Parameter.PARAMETER_NAME_USER_PWD);
			try {
				userModel =	ProviderFactory.createUserServiceProvider().login(
						account, password);
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}else{
			return "1";
		}
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		if("0".equals(result)){
			if(null!=userModel){
				StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_TOKEN, userModel.getToken());
			}
			if(null!=loginListenner){
				loginListenner.onLoginSuccesed();
			}
		}else if(!"1".equals(result)){
			if(null!=loginListenner&&isJumpLogin){
				GlobalConfig.getInstance().setShoppingCartChange(true);
				StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_IS_LOGIN,
						"false");
				//用户登出清空记住的CID
				StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, null);
				com.weipu.common.util.GlobalConfig.getInstance().getUserSessionCfg().setCustomerid(null);
				loginListenner.onLoginFailed();
			}
		}
	}

}
